package com.wangjiacai.utils.ali.tts.service.impl;

import com.alibaba.nls.client.protocol.OutputFormatEnum;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerListener;
import com.alibaba.nls.client.protocol.tts.SpeechSynthesizerResponse;
import com.wangjiacai.utils.ali.NettyConnection;
import com.wangjiacai.utils.ali.tts.AliTtsPool;
import com.wangjiacai.utils.ali.tts.Voice;
import com.wangjiacai.utils.ali.tts.service.TtsService;
import com.wangjiacai.utils.utils.BytesUtil;
import org.springframework.stereotype.Service;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Consumer;

@Service
public class TtsServiceImpl implements TtsService {

    private NettyConnection getNettyConnection(AliTtsPool aliTtsPool, Consumer<byte[]> consumer)throws Exception {
         return aliTtsPool.getConnection(new SpeechSynthesizerListener() {
            List<byte[]> list = new ArrayList<>();
            @Override
            public void onComplete(SpeechSynthesizerResponse speechSynthesizerResponse) {
                consumer.accept( BytesUtil.getAllBytes(list));
            }

            @Override
            public void onMessage(ByteBuffer byteBuffer) {
                int size = byteBuffer.remaining();
                byte[] bytes = new byte[size];
                byteBuffer.get(bytes);
                list.add(bytes);
            }

        });
    }

    @Override
    public CompletableFuture<byte[]> getBytesByText(AliTtsPool aliTtsPool, String text) throws Exception {
        return getBytesByText(aliTtsPool,OutputFormatEnum.WAV,Voice.StandWomenVoiceXY,text);
    }

    @Override
    public CompletableFuture<byte[]> getBytesByText(AliTtsPool aliTtsPool, OutputFormatEnum format, String text) throws Exception {
        return getBytesByText(aliTtsPool,format,Voice.StandWomenVoiceXY,text);
    }

    @Override
    public CompletableFuture<byte[]> getBytesByText(AliTtsPool aliTtsPool, OutputFormatEnum format, Voice voice ,String text) throws Exception {
        CompletableFuture<byte[]> cf = new CompletableFuture<>();
        NettyConnection connection=getNettyConnection(aliTtsPool,bytes->{
            cf.complete(bytes);
        });
        connection.sendTtsText(text,format,voice);
        return cf;
    }
}
